package com.time.store.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.store.auth.entity.bo.Modules;
import com.time.store.auth.entity.bo.RoleModules;
import com.time.store.auth.entity.bo.Roles;
import com.time.store.auth.entity.bo.UserRoles;
import com.time.store.auth.entity.dto.AddUserSetRoleReq;
import com.time.store.auth.entity.dto.RolePageQueryReq;
import com.time.store.auth.entity.vo.RoleListRes;
import com.time.store.auth.mapper.RolesMapper;
import com.time.store.core.util.AuthUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author 时间
 * @since 2021-04-25
 */
@Service
public class RolesService extends ServiceImpl<RolesMapper, Roles> implements IService<Roles> {
    @Autowired
    private UserRolesService userRolesService;

    /**
     * 根据用户id查询所有角色Id
     *
     * @param userId
     * @return
     */
    public List<Integer> getByUserId(Integer userId) {
        return userRolesService
                .lambdaQuery()
                .eq(UserRoles::getUserId, userId)
                .list()
                .stream()
                .map(UserRoles::getRoleId)
                .collect(Collectors.toList());
    }

    public Page<Roles> pageRole(RolePageQueryReq rolePageQueryReq) {
        IPage<Roles> rolePage = new Page<>(rolePageQueryReq.getCurrent(), rolePageQueryReq.getSize());
        return baseMapper.pageRole(rolePage, rolePageQueryReq);
    }

    public List<RoleListRes> listByUserId(Integer userId) {
        return baseMapper.listByUserId(userId);
    }

    /**
     * 给用户设置角色
     *
     * @param addUserSetRoleReqs
     * @return
     */
    public Boolean updateUserRole(AddUserSetRoleReq addUserSetRoleReqs) {
        // 删除之前用户配置角色
        QueryWrapper<UserRoles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", addUserSetRoleReqs.getUserId());
        queryWrapper.eq("store_id", AuthUtil.getCurrStoreId());
        userRolesService.remove(queryWrapper);
        return userRolesService.saveBatch(addUserSetRoleReqs.getRoleIds().stream().map(item -> {
            UserRoles userRoles = new UserRoles();
            userRoles.setStoreId(AuthUtil.getCurrStoreId());
            userRoles.setUserId(addUserSetRoleReqs.getUserId());
            userRoles.setRoleId(item);
            return userRoles;
        }).collect(Collectors.toList()));
    }


}
